package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {

    @Autowired
    private EmpService empService;

    @Autowired
    @Lazy //使用 @Lazy 延迟加载其中一个依赖
    private StudentService studentService;

    /**
     * 分页查询
     * @param clazzQueryParam
     * @return
     */
    @Override
    public PageResult<Clazz> getPageResult(ClazzQueryParam clazzQueryParam) {
        //1.设置查询条件
        Page<Clazz> page = Page.of(clazzQueryParam.getPage(), clazzQueryParam.getPageSize());
        //2.开启分页查询
        //构建查询条件构造器
        LambdaQueryWrapper<Clazz> queryWrapper = new LambdaQueryWrapper<>();
        //模糊匹配、日期匹配
        queryWrapper.like(clazzQueryParam.getName() != null && !clazzQueryParam.getName().isEmpty(), Clazz::getName, clazzQueryParam.getName())
                .between(clazzQueryParam.getBegin() != null && clazzQueryParam.getEnd() != null, Clazz::getBeginDate, clazzQueryParam.getBegin(), clazzQueryParam.getEnd());

        //设置修改时间倒序
        page.addOrder(OrderItem.desc("update_time"));

        //3.调用page方法完成分页查询
        page = page(page, queryWrapper);

        //查询员工数据--班主任姓名
        List<Clazz> clazzList = page.getRecords();
        //获取masterId
        Set<Integer> masterIds = clazzList.stream().map(Clazz::getMasterId).collect(Collectors.toSet());

        //根据masterId查询masterName
        if (!masterIds.isEmpty()) {
            List<Emp> masters = empService.listByIds(masterIds);

            //将班主任-员工数据封装为Map集合
            Map<Integer, String> masterMap = masters.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
            //遍历map
            clazzList.forEach(master -> {
                master.setMasterName(masterMap.getOrDefault(master.getMasterId(), null));
            });
        }

        //设置开班状态status,
        // - 当前时间 < 开课时间：未开课
        //   - 当前时间 > 结课时间：已结课
        //   - 否则：在读
        clazzList.forEach(clazz -> {
            if (LocalDate.now().isBefore(clazz.getBeginDate())) {
                clazz.setStatus("未开课");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        });

        return new PageResult<>(page.getTotal(), clazzList);
    }

    /**
     * 添加班级信息
     * @param clazz
     */
    @Override
    public void saveClazz(Clazz clazz) {
    //  保存班级的基本信息
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
    //save()
        save(clazz);

    }

    /**
     * 修改班级信息
     * @param clazz
     */
    @Override
    public void updateClazz(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }

    /**
     * 根据id删除班级信息 如果该班级下有关联的学生，则不允许删除，并提示错误信息
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //count(LambdaQueryWrapper)构建查询条件 clazz_id = id
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getClazzId, id);

        //查询是否有关联学生
        int count = (int) studentService.count(queryWrapper);
        if (count > 0) {
            throw new RuntimeException("对不起, 该班级下有学生, 不能直接删除");
        }
        //没有关联的学生，则可以安全删除
        removeById(id);
    }
}
